<!--
 * @Descripttion: 
 * @version: 
 * @Author: lsy
 * @Date: 2021-12-16 17:29:42
 * @LastEditors: lsy
 * @LastEditTime: 2021-12-17 15:34:59
-->
<template>
    <div>
        {{ clientType }}
        <!--快速导航页-->
        <home-add
            :uType="uType"
            @collect="collect"
            @showAdd="showNavColl"
            v-if="isShowAdd"
            :bigMenuDic="bigMenuDic"
            @toUrl="tomenuPath"
            :allMenus="souceData"
            :recentVistData="visitHistory"
            :collectNav="collectNav"
        ></home-add>
    </div>
</template>
<script>
import { clientObj, initClient } from '@/utils/client.js';
import homeAdd from "./homeAdd.vue"
export default {
    components: { homeAdd },
    name: "clientHome",
    data() {
        return {
            //已经访问的菜单
            visNavData: [],
            //收藏的快捷导航
            collectNav: [],
            //所有导航
            souceData: [],
            //当前需要生产的iframe数据源
            framesData: [],
            isShowAdd: true,
            uType: 2,

            //大类菜单http://192.168.3.35:8080/zrd/#/home/2?token=1:cee5ddf4-3d28-4747-bc4b-23b8ee2d05f9
            bigMenuDic: [],
            //最近访问
            visitHistory: [],

            clientType: "qewqewqewqewq"
        }
    },
    async created() {
        localStorage.setItem("evo-brm", "1.2.0")

        let clientType = this.$route.params.clientType;
        localStorage.clientType = clientType;

        let accessToken = this.$route.query.token;
        const lang = this.$route.query.locale;
        const skin = this.$route.query.skin;

        localStorage.accessToken = accessToken;

        localStorage.userId = localStorage.userId ? localStorage.userId : localStorage.accessToken ? localStorage.accessToken.split(':')[0] : ''
        this.$i18n.locale = lang
        localStorage.language = lang
        localStorage.skin = skin
        document.getElementsByTagName('body')[0].className += `client-${skin}-theme`

        let that = this;

        initClient.then(() => {
            clientObj.connectRPCNotify((method, msg) => {
                let data = msg
                switch (method) {
                    case 'closeMenu': {
                        console.log('closeMenu')
                        break
                    }
                    case 'changeMenu': {
                        let d = JSON.parse(msg)
                        let param = {
                            uniqueMenuCode: d.toMenuCode
                        }
                        if (d.toMenuCode === 'CLIENT_001' || d.toMenuCode === 'CLIENT_002' || d.toMenuCode === 'CLIENT_003') {
                            // that.getHistoryVisit()
                            if (d.toMenuCode === 'CLIENT_001') {
                                that.showAdd()
                            }
                            return
                        }
                        that.setVisNavData(param).then(() => {
                            // that.menuPathChange()
                            // that.getHistoryVisit()
                        })
                        break
                    }
                    case 'closeAllMenu':
                        console.log('closeAllMenu')
                        break
                    case 'changeToken':
                        localStorage.accessToken = data
                        break
                    default:
                        break
                }
            })
        }).catch(err => {
            // console.log(err)
        })

    },
    async mounted() {
        await initClient.then((d) => {
            localStorage.clientType = 2
            console.log('localStorage.clientType1', localStorage.clientType)
            this.clientType = localStorage.clientType;
        }).catch((e) => {
            this.clientType = e;
            localStorage.clientType = 1
            console.log('localStorage.clientType2', localStorage.clientType)
        })
        this.showAdd()
    },
    methods: {
        /**
         * @method showAdd() 点击加号
         * @param {Boolean} bl true代表首次进入
         */
        async showAdd(refresh, bl) {
            if (!refresh) {
                this.isShowAdd = true
            }
            this.visNavData.map((item) => {
                item.isActive = false
                return item
            })
            // let type = localStorage.clientType === '2' ? 2 : 1
            // if (type === 2) {
            //     await util.mergeLanguage(localStorage.language, this, 'evo-wpms')
            // }

            VE_API.menu.getNavigation({}, `?terminal=2`).then(res => {
                let data = res.data.data;

                //获取所有菜单
                this.collectNav = []
                let obj = {}
                const framesData = this.framesData
                data.value.forEach((element) => {
                    element.menus.forEach((item) => {
                        let key = item.uniqueMenuCode.split('_')[0]
                        //日志前端写在了brm中，所以作此操作
                        key = key === 'EVOLOG' ? 'EVOBRM' : key
                        let cM = framesData.find(d => d.key === key)
                        if (cM) {
                            !cM.paths.includes(item.menuPath) && cM.paths.push(item.menuPath)
                        } else {
                            obj[key] = 1
                            let param = { key: key, paths: [], oldPath: '', uniqueMenuCode: item.uniqueMenuCode }
                            param.paths.push(item.menuPath)
                            framesData.push(param)
                        }
                        item.menuName = item.customNameFlag ? this.$t(item.menuName) : this.$t(item.menuRegroupName || item.uniqueMenuCode)
                        item.showHomeIcon = item.menuHomeIcon ? '/evo-apigw/evo-oss/' + item.menuHomeIcon + '?token=' + localStorage.accessToken : item.menuStaticHomeIcon ? item.menuStaticHomeIcon : ''
                        item.showName = item.menuName.length > 6 ? item.menuName.substring(0, 6) + '...' : item.menuName
                        item.isC && this.collectNav.push(item)
                    })
                })
                if (bl) {
                    framesData.push({ key: 'NOTICK', oldPath: '', paths: [] })
                    framesData.push({ key: 'TASK', oldPath: '', paths: [] })
                }
                this.framesData = framesData
                this.collectNav.sort(function (a, b) {
                    return a.sort - b.sort
                })
                this.souceData = [...data.value]
            })
        },
        /**@augments
         * @method setVisNavData() 设置页签中导航的状态
         * @param {Object} data 当前将要设置页签对象（比如从快捷页跳转时）
         */
        setVisNavData(data) {
            return new Promise((resolve, reject) => {
                let cItem = ''
                if (data) {
                    cItem = this.visNavData.find(item => item.uniqueMenuCode === data.uniqueMenuCode)
                    if (!cItem) {
                        if (this.visNavData.length === 10 && localStorage.clientType !== '2') {
                            //打开的菜单达到上限，请关闭不用的菜单
                            this.$message.warning(this.$t('home.menuCeiling'))
                            localStorage.visNavData = JSON.stringify(this.visNavData)
                            resolve(false)
                            return
                        }
                        this.visNavData.push(data)
                    }
                }
                this.visNavData.map((item) => {
                    item.isActive = false
                    return item
                })
                let cData = cItem ? cItem : data
                if (cData) {
                    cData.isActive = true
                }
                localStorage.visNavData = JSON.stringify(this.visNavData)
                this.uniqueMenuCode = cData.uniqueMenuCode
                resolve(true)
            })
        },
        /**@augments
         * @method collect() 是否收藏
         * @param {Object} item 当前的收藏项对象
         */
        collect(item) {
            let str = !item.isC ? this.$t('添加收藏成功') : this.$t('已取消收藏')
            item.isC = !item.isC
            let currentIndex = 0
            let d = this.collectNav.find((data, index) => {
                if (data.uniqueMenuCode === item.uniqueMenuCode) {
                    currentIndex = index
                    return data
                }
            })
            if (item.isC) {
                if (!d) {
                    this.collectNav.push(item)
                }
            } else {
                if (d) {
                    this.collectNav.splice(currentIndex, 1)
                }
            }
            Message.success(str)
            this.setCollect()
        },
        /**@augments
         * @method setCollect() 设置快捷导航
         */
        setCollect() {
            let arr = []
            this.collectNav.forEach((item, n) => {
                arr.push({
                    uniqueMenuCode: item.uniqueMenuCode,
                    sort: n + ''
                })
                item.sort = n + ''
            })
            // factory.setFastNav({
            //     navigationInfos: arr
            // })
        },

        /**@augments
                * @method showNavColl() 是否展开快速收藏页，展开时导航页签栏收起
                */
        showNavColl(bl) {
            // this.isNavCollLeave = false
            // let time = bl ? 0 : 400
            // // 重置导航搜索状态
            // this.emitEmpty()
            // setTimeout(() => {
            //     if (this.isNavCollLeave) {
            //         return
            //     }
            //     // this.isShowNav = false
            //     this.visible = true
            //     this.collectNav = []
            //     let collectArr = []
            //     //获取所有菜单
            //     let type = localStorage.clientType === '2' ? 2 : 1
            //     factory.getAllMenu(type).then((res) => {
            //         let data = res.value
            //         data.forEach((element) => {
            //             element.menus.forEach((item) => {
            //                 item.menuName = item.customNameFlag ? this.$t(item.menuName) : this.$t(item.menuRegroupName || item.uniqueMenuCode)
            //                 item.showHomeIcon = item.menuHomeIcon ? '/evo-apigw/evo-oss/' + item.menuHomeIcon + '?token=' + localStorage.accessToken : item.menuStaticHomeIcon ? item.menuStaticHomeIcon : ''
            //                 item.showName = item.menuName.length > 6 ? item.menuName.substring(0, 6) + '...' : item.menuName
            //                 item.isC && collectArr.push(item)
            //             })
            //         })
            //         this.souceData = [...data]
            //         collectArr.sort(function (a, b) {
            //             return a.sort - b.sort
            //         })
            //         this.collectNav = [...collectArr]
            //     })
            //     //获取最近访问菜单
            //     // this.getHistoryVisit()
            //     this.isNavCollLeave = false
            //     this.openColl()
            // }, time)
        },

        /**@augments
         * @method tomenuPath() 打开导航菜单
         * @param {Object} item 当前要打开的导航对象
         */
        tomenuPath(item) {
            console.log("wqewqewqewq", item);

            if (item.parentMenuPath) {
                this.framesData.map((frameItem) => {
                    if (frameItem.paths.includes(item.parentMenuPath)) {
                        frameItem.mjnow = true
                    } else {
                        frameItem.mjnow = false
                    }
                    return frameItem
                })
                item.uniqueMenuCode = item.parentCode
                item.menuPath = item.menuPath.includes('?path=') ? item.menuPath : item.parentMenuPath + '?path=' + item.menuPath
            }
            if (item.customNameFlag) {
                let rgx = /^(http)|(https)$/
                let path = rgx.test(item.menuPath) ? item.menuPath : 'http://' + item.menuPath
                if (!this.uType) {
                    window.open(path, '_blank')
                    return
                }
            }
            let param = { ...item }
            param.isActive = true
            item.router === 'notick' && item.router === '' ? "" : localStorage.cMenuItem = JSON.stringify(param)
            if (localStorage.clientType === '2') {
                clientObj.openMenu(item.uniqueMenuCode)
                this.setVisNavData(param).then((bl) => {
                    if (bl) {
                        this.cmenuPath = item.menuPath
                        let key = item.uniqueMenuCode.split('_')[0]
                        let cM = this.framesData.find(d => d.key === key)
                        cM.oldPath = this.cmenuPath
                        // this.menuPathChange()
                    }
                })
                return
            }
            // if (!item.customNameFlag) {
            //     this.setVisNavData(param).then((bl) => {
            //         if (bl) {
            //             this.onClose()
            //             this.isShowAdd = false
            //             this.cmenuPath = item.menuPath
            //             let key = item.uniqueMenuCode.split('_')[0]
            //             let cM = this.framesData.find(d => d.key === (key === 'EVOLOG' ? 'EVOBRM' : key))
            //             cM.oldPath = this.cmenuPath
            //             this.ieReload()
            //             if (key === 'NOTICK') {
            //                 let arr = JSON.parse(localStorage.visNavDat)
            //                 arr.forEach(val => {
            //                     if (val.uniqueMenuCode.indexOf(key) > -1) {
            //                         val.menuPath = item.menuPath
            //                     }
            //                 })
            //                 this.framesData[this.framesData.length - 2].paths.push(item.menuPath)
            //                 this.visNavDat = localStorage.visNavDat = JSON.stringify(arr)
            //                 return
            //             } else if (key === 'TASK') {
            //                 let visNavDatarr = localStorage.getItem('visNavData')
            //                 visNavDatarr = visNavDatarr ? JSON.parse(visNavDatarr) : []
            //                 this.framesData[this.framesData.length - 1].paths.push(item.menuPath)
            //                 if (visNavDatarr.length) {
            //                     visNavDatarr.forEach(val => {
            //                         if (val.uniqueMenuCode.indexOf(key) > -1) {
            //                             val.menuPath = item.menuPath
            //                         }
            //                     })
            //                 }
            //                 this.visNavDat = localStorage.visNavDat = JSON.stringify(visNavDatarr)
            //                 return
            //             }
            //             this.$forceUpdate()
            //             // this.menuPathChange()
            //         }
            //     })
            // }
        },
    }
}
</script>
